"""
Market Data Service V2 - Main Entry Point
==========================================

基于全新适配器架构的市场数据服务入口

架构亮点：
1. 完全配置驱动 - 所有适配器通过配置加载
2. 依赖注入 - 所有服务通过构造函数注入依赖
3. 插件化 - 可以动态添加新的适配器而无需修改代码
4. 解耦 - MarketDataService不依赖任何具体的数据源或数据库实现

作者: 架构组
创建日期: 2025-10-05
版本: v2.0
"""

import sys
import os
from pathlib import Path
import logging
from contextlib import asynccontextmanager
from dotenv import load_dotenv
from typing import Optional

# 确保路径设置
# __file__ -> app/main.py
# parent -> app/
# parent.parent -> market_data_service/
# parent.parent.parent -> services/
# parent.parent.parent.parent -> backend/
# parent.parent.parent.parent.parent -> redfire/ (project root)
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))

# 加载环境变量
service_dir = Path(__file__).parent.parent
env_file = service_dir / "config" / "development.env"
if env_file.exists():
    load_dotenv(env_file)

from fastapi import FastAPI, Request, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
import redis.asyncio as redis

# 导入RedFire框架
from backend.redfire_framework.logging.manager import configure_logging
from backend.redfire_framework.monitoring import get_metrics_manager, increment, set_gauge

# 导入服务配置
from backend.services.market_data_service.config.service_config import get_config

# 导入新架构的核心组件
from backend.services.market_data_service.app.adapters.manager import AdapterManager
from backend.services.market_data_service.app.services.core.market_data_service_v2 import MarketDataServiceV2
from backend.services.market_data_service.app.services.core.influxdb_writer_service import InfluxDBWriterService
from backend.services.market_data_service.app.services.core.cache_service import CacheService

# 导入API路由（V2版本）
from backend.services.market_data_service.app.api.market_data_routes import router as market_data_router

# 导入WebSocket广播服务
from backend.services.market_data_service.app.services.websocket.broadcaster import (
    initialize_broadcaster,
    cleanup_broadcaster,
    BroadcastConfig
)

# 导入异常
from backend.services.market_data_service.exceptions.market_data_exceptions import (
    MarketDataException,
    DataSourceException,
    CacheException
)

# 导入依赖注入模块
from backend.services.market_data_service.app import dependencies

# 导入异常处理器
from backend.services.market_data_service.app.api.exception_handlers import register_exception_handlers

# NOTE: 全局服务实例已弃用，改用dependencies模块管理
# _adapter_manager: AdapterManager = None
# _market_data_service: MarketDataServiceV2 = None
# _writer_service: InfluxDBWriterService = None
# _cache_service: CacheService = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    
    启动流程：
    1. 加载配置
    2. 初始化 AdapterManager（自动加载所有配置的适配器）
    3. 初始化 WriterService
    4. 初始化 CacheService
    5. 初始化 MarketDataServiceV2（注入所有依赖）
    6. 运行健康检查
    
    关闭流程：
    1. 清理 MarketDataServiceV2
    2. 清理 AdapterManager（自动清理所有适配器）
    3. 清理其他服务
    """
    # 不再使用全局变量，改用局部变量和依赖注入模块
    # global _adapter_manager, _market_data_service, _writer_service, _cache_service
    
    adapter_manager: Optional[AdapterManager] = None
    writer_service: Optional[InfluxDBWriterService] = None
    cache_service: Optional[CacheService] = None
    market_data_service: Optional[MarketDataServiceV2] = None
    redis_pool: Optional[redis.ConnectionPool] = None
    broadcaster = None

    logger = logging.getLogger(__name__)
    logger.info("=" * 80)
    logger.info("🚀 Market Data Service V2 Starting Up...")
    logger.info("=" * 80)
    
    try:
        # 1. 加载配置
        config = get_config()
        logger.info(f"✅ Configuration loaded: {config.service_name} v{config.service_version}")
        logger.info(f"   - InfluxDB: {config.database.influxdb_url}")
        logger.info(f"   - Redis: redis://{config.database.redis_host}:{config.database.redis_port}/{config.database.redis_db}")
        
        # 2. 初始化 AdapterManager
        logger.info("📦 Initializing AdapterManager...")
        adapter_manager = AdapterManager(config=config)
        await adapter_manager.initialize()
        
        adapters = adapter_manager.list_adapters()
        logger.info(f"✅ AdapterManager initialized with {len(adapters)} adapters: {adapters}")
        
        # 3. 初始化 WriterService (可选，如果InfluxDB未配置则跳过)
        logger.info("💾 Initializing InfluxDBWriterService...")
        # 从 adapter_manager 获取 InfluxDB 适配器
        influxdb_adapter = adapter_manager.get_adapter('influxdb')
        if influxdb_adapter:
            writer_service = InfluxDBWriterService(adapter=influxdb_adapter)
            await writer_service.start()
            logger.info("✅ InfluxDBWriterService initialized")
        else:
            writer_service = None
            logger.warning("⚠️ InfluxDB adapter not available, InfluxDBWriterService will not be started")
            logger.warning("   Time-series data storage will be disabled")
        
        # 4. 初始化 CacheService
        logger.info("🗄️  Initializing CacheService...")
        redis_pool = redis.ConnectionPool.from_url(
            config.database.redis_url,
            decode_responses=False  # Pickle returns bytes
        )
        cache_service = CacheService(connection_pool=redis_pool)
        logger.info("✅ CacheService initialized")
        
        # 5. 初始化 MarketDataServiceV2
        logger.info("🎯 Initializing MarketDataServiceV2...")
        market_data_service = MarketDataServiceV2(
            adapter_manager=adapter_manager,
            writer_service=writer_service,
            cache_service=cache_service
        )
        logger.info("✅ MarketDataServiceV2 initialized")
        
        # 6. 注册依赖到依赖注入模块
        logger.info("📌 Registering dependencies...")
        dependencies.set_adapter_manager(adapter_manager)
        dependencies.set_market_data_service(market_data_service)
        dependencies.set_cache_service(cache_service)
        logger.info("✅ Dependencies registered")
        
        # 7. 运行健康检查
        logger.info("🏥 Running startup health check...")
        health_status = await market_data_service.health_check()
        
        if health_status["status"] == "healthy":
            logger.info("✅ All components are healthy")
        else:
            logger.warning(f"⚠️  Some components are unhealthy: {health_status}")
        
        # 8. 初始化WebSocket广播服务
        logger.info("📡 Initializing WebSocket broadcaster...")
        try:
            # 配置广播服务
            broadcast_config = BroadcastConfig(
                update_interval=5,  # 每5秒更新一次
                enabled=True,
                batch_size=10,
                max_retries=3
            )
            
            broadcaster = await initialize_broadcaster(
                market_data_service=market_data_service,
                config=broadcast_config
            )
            logger.info("✅ WebSocket broadcaster initialized and started")
        except Exception as e:
            logger.error(f"⚠️  Failed to initialize broadcaster: {e}", exc_info=True)
            broadcaster = None
        
        # 9. 记录启动指标
        increment("service_startups_total")
        set_gauge("service_startup_health", 1 if health_status["status"] == "healthy" else 0)
        
        logger.info("=" * 80)
        logger.info("✨ Market Data Service V2 Started Successfully!")
        logger.info("=" * 80)
        
        yield
        
    except Exception as e:
        logger.error(f"❌ Failed to start Market Data Service V2: {e}", exc_info=True)
        increment("service_startup_failures_total")
        raise
    
    finally:
        logger.info("=" * 80)
        logger.info("🛑 Market Data Service V2 Shutting Down...")
        logger.info("=" * 80)
        
        # 记录关闭指标
        increment("service_shutdowns_total")
        
        # 清理广播服务
        if broadcaster:
            logger.info("📡 Cleaning up broadcaster...")
            await cleanup_broadcaster()
        
        # 清理依赖注入
        logger.info("📌 Clearing dependencies...")
        dependencies.clear_dependencies()
        
        # 清理服务（按相反顺序）
        if writer_service:
            logger.info("💾 Cleaning up WriterService...")
            await writer_service.cleanup()
        
        if cache_service:
            logger.info("🗄️  Cleaning up CacheService...")
            await cache_service.close() # 使用新的 close 方法
        
        if adapter_manager:
            logger.info("📦 Cleaning up AdapterManager...")
            await adapter_manager.cleanup()
        
        if redis_pool:
            logger.info("🔌 Disposing Redis connection pool...")
            await redis_pool.disconnect()

        logger.info("=" * 80)
        logger.info("✅ Market Data Service V2 Shutdown Complete")
        logger.info("=" * 80)


def create_app() -> FastAPI:
    """创建并配置FastAPI应用程序实例"""
    
    # 配置日志
    configure_logging({"level": "INFO"})
    
    logger = logging.getLogger(__name__)
    
    app = FastAPI(
        title="Market Data Service V2",
        description="基于插件化适配器架构的专业市场数据服务API",
        version="2.0.0",
        lifespan=lifespan
    )
    
    # 添加CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 包含API路由
    app.include_router(market_data_router, prefix="/api/v1", tags=["market-data"])
    
    # 注册异常处理器（使用新的统一异常处理器）
    register_exception_handlers(app)
    logger.info("✅ Exception handlers registered")
    
    # ==================== 健康检查端点 ====================
    
    @app.get("/health", tags=["health"])
    async def health_check():
        """基本健康检查端点"""
        return {
            "status": "healthy",
            "service": "market_data_service_v2",
            "version": "2.0.0"
        }
    
    @app.get("/health/detailed", tags=["health"])
    async def get_detailed_health(
        service: MarketDataServiceV2 = Depends(dependencies.get_market_data_service_optional)
    ):
        """获取详细的健康检查结果"""
        try:
            if not service:
                raise HTTPException(status_code=503, detail="Service not initialized")
            
            health_status = await service.health_check()
            
            return health_status
            
        except Exception as e:
            logger.error(f"Failed to perform health check: {e}")
            raise HTTPException(status_code=500, detail=f"Health check failed: {str(e)}")
    
    # ==================== 监控端点 ====================
    
    @app.get("/metrics", tags=["monitoring"])
    async def get_metrics():
        """获取Prometheus格式的指标"""
        try:
            metrics_manager = get_metrics_manager()
            metrics = await metrics_manager.collect_all()
            
            # 转换为Prometheus格式
            prometheus_output = []
            for metric in metrics:
                labels = ",".join([f'{k}="{v}"' for k, v in metric.labels.items()]) if metric.labels else ""
                label_str = f"{{{labels}}}" if labels else ""
                prometheus_output.append(f"{metric.name}{label_str} {metric.value}")
            
            return "\n".join(prometheus_output)
            
        except Exception as e:
            logger.error(f"Failed to collect metrics: {e}")
            raise HTTPException(status_code=500, detail="Failed to collect metrics")
    
    # ==================== 信息端点 ====================
    
    @app.get("/info/adapters", tags=["info"])
    async def get_adapters_info(
        service: MarketDataServiceV2 = Depends(dependencies.get_market_data_service_optional)
    ):
        """获取所有适配器的信息"""
        try:
            if not service:
                raise HTTPException(status_code=503, detail="Service not initialized")
            
            adapters = service.get_available_adapters()
            adapter_info = service.get_adapter_info()
            
            return {
                "total": len(adapters),
                "adapters": adapters,
                "details": adapter_info
            }
            
        except Exception as e:
            logger.error(f"Failed to get adapters info: {e}")
            raise HTTPException(status_code=500, detail=f"Failed to get adapters info: {str(e)}")
    
    @app.get("/info/service", tags=["info"])
    async def get_service_info():
        """获取服务信息"""
        from datetime import datetime
        
        return {
            "service": "market_data_service",
            "version": "2.0.0",
            "architecture": "v2-plugin-based",
            "timestamp": datetime.now().isoformat(),
            "features": [
                "插件化适配器架构",
                "配置驱动的数据源切换",
                "完全解耦的服务设计",
                "依赖注入",
                "健康检查和监控",
                "多数据源支持（Tushare, CTP, InfluxDB）",
                "实时数据订阅",
                "历史数据查询",
                "自动数据持久化",
                "多级缓存",
            ]
        }
    
    logger.info("FastAPI application created successfully")
    
    return app


# 创建应用实例
app = create_app()


# 依赖注入函数（供API路由使用）
# 注意：这些函数已弃用，请使用 app.dependencies 模块中的函数
async def get_market_data_service() -> MarketDataServiceV2:
    """
    获取MarketDataServiceV2实例的依赖注入函数（已弃用）
    
    请使用: from app.dependencies import get_market_data_service
    """
    return await dependencies.get_market_data_service()


async def get_adapter_manager() -> AdapterManager:
    """获取AdapterManager实例的依赖注入函数（已弃用）
    
    请使用: from app.dependencies import get_adapter_manager
    """
    return await dependencies.get_adapter_manager()


# 入口点用于直接运行服务
if __name__ == "__main__":
    import uvicorn
    
    # 从配置读取端口
    config = get_config()
    port = config.api_port
    
    print(f"🚀 Starting Market Data Service V2 on port {port}...")
    print(f"📖 API docs: http://localhost:{port}/docs")
    print(f"🏥 Health check: http://localhost:{port}/health")
    print(f"📊 Metrics: http://localhost:{port}/metrics")
    print(f"ℹ️  Service info: http://localhost:{port}/info/service")
    print(f"📦 Adapters info: http://localhost:{port}/info/adapters")
    
    uvicorn.run(app, host="0.0.0.0", port=port)